package com.rd.student.jiaji.class1.lixin;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Random2 {

    public static List<String> randomStudentsFromFile(String filename, int n) {
        List<String> allStudents = new ArrayList<>();

        // 读取文件
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                allStudents.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return randomStudents(allStudents, n);
    }

    public static List<String> randomStudents(List<String> students, int n) {
        List<String> selectedStudents = new ArrayList<>();

        // 确保个数不超过学生总数
        n = Math.min(n, students.size());

        // 随机选择n个同学
        Random random = new Random();
        while (selectedStudents.size() < n) {
            int index = random.nextInt(students.size());
            selectedStudents.add(students.get(index));
            students.remove(index);
        }

        return selectedStudents;
    }

    public static void main(String[] args) {
        String filename = "all.txt";
        int n = 5;

        List<String> selectedStudents = randomStudentsFromFile(filename, n);

        System.out.println("随机选择的同学列表：");
        for (String student : selectedStudents) {
            System.out.println(student);
        }
    }
}
